package com.example.smartagrisys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.smartagrisys.common.utils.FileUtil;
import com.example.smartagrisys.entity.SellerProduct;
import com.example.smartagrisys.mapper.SellerProductMapper;
import com.example.smartagrisys.service.SellerProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 卖家商品服务实现类
 */
@Slf4j
@Service
public class SellerProductServiceImpl extends ServiceImpl<SellerProductMapper, SellerProduct> implements SellerProductService {

    @Autowired
    private FileUtil fileUtil;

    @Override
    public IPage<SellerProduct> getSellerProductPage(Page<SellerProduct> page, Long sellerId, String category, Integer status, String keyword) {
        QueryWrapper<SellerProduct> queryWrapper = new QueryWrapper<>();
        
        // 设置查询条件
        if (sellerId != null) {
            queryWrapper.eq("seller_id", sellerId);
        }
        
        if (!StringUtils.isEmpty(category)) {
            queryWrapper.eq("category", category);
        }
        
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        if (!StringUtils.isEmpty(keyword)) {
            queryWrapper.and(wrapper -> wrapper
                    .like("name", keyword)
                    .or()
                    .like("description", keyword));
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc("create_time");
        
        return page(page, queryWrapper);
    }

    @Override
    public List<SellerProduct> getSellerProducts(Long sellerId) {
        if (sellerId == null) {
            return new ArrayList<>();
        }
        
        log.info("获取卖家商品列表, 卖家ID: {}", sellerId);
        
        LambdaQueryWrapper<SellerProduct> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SellerProduct::getSellerId, sellerId);
        queryWrapper.orderByDesc(SellerProduct::getCreateTime);
        
        List<SellerProduct> products = list(queryWrapper);
        
        // 处理列表数据，确保certificatesList和suitableCropsList正确
        for (SellerProduct product : products) {
            // 获取并设置certificatesList和suitableCropsList
            product.getCertificatesList();
            product.getSuitableCropsList();
        }
        
        log.info("获取到{}条商品数据", products.size());
        return products;
    }

    @Override
    public SellerProduct getSellerProductById(Long id) {
        return getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addSellerProduct(SellerProduct product) {
        log.info("添加商品：{}", product);

        product.setCreateTime(LocalDateTime.now());
        product.setUpdateTime(LocalDateTime.now());
        
        // 初始状态为下架
        if (product.getStatus() == null) {
            product.setStatus(0);
        }
        
        product.setSales(0); // 初始销量为0
        
        // 生成商品编号
        if (product.getProductCode() == null || product.getProductCode().isEmpty()) {
            product.setProductCode("P" + System.currentTimeMillis() % 100000000);
            log.info("生成商品编号: {}", product.getProductCode());
        }
        
        // 处理证书列表和适宜作物列表
        List<String> certificatesList = product.getCertificatesList();
        if (certificatesList != null && !certificatesList.isEmpty()) {
            try {
                // 使用ObjectMapper将列表转换为JSON字符串
                ObjectMapper objectMapper = new ObjectMapper();
                product.setCertificates(objectMapper.writeValueAsString(certificatesList));
            } catch (Exception e) {
                log.error("转换certificates为JSON失败", e);
                product.setCertificates(String.join(",", certificatesList));
            }
        }
        
        List<String> suitableCropsList = product.getSuitableCropsList();
        if (suitableCropsList != null && !suitableCropsList.isEmpty()) {
            try {
                // 使用ObjectMapper将列表转换为JSON字符串
                ObjectMapper objectMapper = new ObjectMapper();
                product.setSuitableCrops(objectMapper.writeValueAsString(suitableCropsList));
            } catch (Exception e) {
                log.error("转换suitableCrops为JSON失败", e);
                product.setSuitableCrops(String.join(",", suitableCropsList));
            }
        }
        
        boolean result = save(product);
        
        if (result) {
            log.info("商品添加成功，ID：{}", product.getId());
        } else {
            log.error("商品添加失败");
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSellerProduct(SellerProduct product) {
        log.info("更新商品：{}", product);
        
        SellerProduct existingProduct = getById(product.getId());
        if (existingProduct == null) {
            log.error("要更新的商品不存在，ID：{}", product.getId());
            return false;
        }
        
        product.setUpdateTime(LocalDateTime.now());
        
        // 确保保留原有图片URL
        if (product.getImage() == null || product.getImage().isEmpty()) {
            product.setImage(existingProduct.getImage());
            log.info("使用原有图片URL: {}", product.getImage());
        }
        
        // 处理证书列表和适宜作物列表
        List<String> certificatesList = product.getCertificatesList();
        if (certificatesList != null && !certificatesList.isEmpty()) {
            try {
                // 使用ObjectMapper将列表转换为JSON字符串
                ObjectMapper objectMapper = new ObjectMapper();
                product.setCertificates(objectMapper.writeValueAsString(certificatesList));
            } catch (Exception e) {
                log.error("转换certificates为JSON失败", e);
                product.setCertificates(String.join(",", certificatesList));
            }
        }
        
        List<String> suitableCropsList = product.getSuitableCropsList();
        if (suitableCropsList != null && !suitableCropsList.isEmpty()) {
            try {
                // 使用ObjectMapper将列表转换为JSON字符串
                ObjectMapper objectMapper = new ObjectMapper();
                product.setSuitableCrops(objectMapper.writeValueAsString(suitableCropsList));
            } catch (Exception e) {
                log.error("转换suitableCrops为JSON失败", e);
                product.setSuitableCrops(String.join(",", suitableCropsList));
            }
        }
        
        boolean result = updateById(product);
        
        if (result) {
            log.info("商品更新成功，ID：{}", product.getId());
        } else {
            log.error("商品更新失败，ID：{}", product.getId());
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSellerProduct(Long id) {
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteSellerProducts(List<Long> ids) {
        return removeByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSellerProductStatus(Long id, Integer status) {
        SellerProduct product = getById(id);
        if (product == null) {
            return false;
        }
        
        product.setStatus(status);
        product.setUpdateTime(LocalDateTime.now());
        
        return updateById(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchUpdateSellerProductsStatus(List<Long> ids, Integer status) {
        if (ids == null || ids.isEmpty() || status == null) {
            return false;
        }
        
        List<SellerProduct> products = listByIds(ids);
        if (products.isEmpty()) {
            return false;
        }
        
        LocalDateTime now = LocalDateTime.now();
        
        for (SellerProduct product : products) {
            product.setStatus(status);
            product.setUpdateTime(now);
        }
        
        return updateBatchById(products);
    }

    @Override
    public String uploadSellerProductImage(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return null;
        }
        
        try {
            return fileUtil.uploadFile(file, "product");
        } catch (Exception e) {
            log.error("上传商品图片失败", e);
            return null;
        }
    }
}
